package com.bonc.common.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

import net.sf.json.JSONArray;
import net.sf.json.JSONNull;
import net.sf.json.JSONObject;



/**
 * Map工具类
 */
public class MapUtils extends HashMap<String, Object> {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public MapUtils put(String key, Object value) {
        super.put(key, value);
        return this;
    }
    
	public static Map<String, Object> nullToEmpty(Map<String, Object> map) {
		Set<String> set = map.keySet();
		if (set != null && !set.isEmpty()) {
			for (String key : set) {
				if (map.get(key) == null) {
					map.put(key, "");
				}
			}
		}
		return map;
	}
	
	/**
     * 将json字符串转为Map结构
     * 如果json复杂，结果可能是map嵌套map
     *
     * @param jsonStr 入参，json格式字符串
     * @return 返回一个map
     */
    public static Map<String, Object> json2Map(String jsonStr) {
        Map<String, Object> map = new HashMap<>();
        if (StringUtils.isNotEmpty(jsonStr)) {
            //jsonStr = Json2Map.replaceBlank(jsonStr);
            //最外层解析
            JSONObject json = JSONObject.fromObject(jsonStr);
            for (Object k : json.keySet()) {
                Object v = json.get(k);
                if (JSONNull.getInstance().equals(v)) {
                    map.put(k.toString(), "");
                    continue;
                }
                //如果内层还是数组的话，继续解析
                if (v instanceof JSONArray) {
                    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                    Iterator<JSONObject> it = ((JSONArray) v).iterator();
                    while (it.hasNext()) {
                        Object obj = it.next();
                        if (obj == null || JSONNull.getInstance().equals(obj)) {
                            continue;
                        }
                        JSONObject json2 = (JSONObject) obj;
                        if (null == json2 || json2.isNullObject() || json2.isEmpty()) {
                            continue;
                        } else {
                            list.add(json2Map(json2.toString()));
                        }
                    }
                    map.put(k.toString(), list);
                } else {
                    map.put(k.toString(), v);
                }
            }
            return map;
        } else {
            return null;
        }
    }
}
